# 创建ConfigParser对象
import configparser

import pymysql

config = configparser.ConfigParser()

# 读取配置文件
config.read("../database_config.ini")

block = 'Database_test'  # 开发环境
# block = 'Database'      # 生产环境

host = config.get(block, 'host')
port = config.get(block, 'port')
username = config.get(block, 'username')
password = config.get(block, 'password')
db_name = config.get(block, 'database')

# 打开数据库连接
db = pymysql.connect(host=host,
                     user=username,
                     password=password,
                     database=db_name)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()


def generate_drop_table_sql(base_table_name, start, end):
    # 生成批量删除表的SQL语句
    drop_table_sql = f"DROP TABLE IF EXISTS {', '.join([f'{base_table_name}_{i}' for i in range(start, end + 1)])};"
    return drop_table_sql


# 定义表名列表
table_names = [
    "jigou",
    "huiyuan",
    "falujianyi",
    "shijikongzhiren",
    "guanlianfangxinxi",
    "chuzirenxinxi",
    "chanpinxixi_xpath",
    "tip"
]

start, end = map(int, input("请输入需要删除的起始页和结束页码(英文逗号隔开)：").split(','))

# 遍历表名列表生成删除语句并执行
for base_table_name in table_names:
    # start = 1
    # end = 13
    sql = generate_drop_table_sql(base_table_name, start, end)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        db.rollback()

# 关闭数据库连接
db.close()
